#!/usr/bin/env python3
"""
打包脚本，用于将后端app打包成wheel文件
"""

import os
import subprocess
import sys
import shutil
from pathlib import Path

def check_prerequisites():
    """检查打包所需的依赖是否已安装"""
    try:
        import setuptools
        import wheel
        import build
        print("✓ 检查依赖: setuptools, wheel, build 均已安装")
    except ImportError as e:
        print(f"✗ 缺少依赖: {e}")
        print("请运行: pip install setuptools wheel build")
        sys.exit(1)

def clean_previous_builds():
    """清理之前的构建文件"""
    print("清理之前的构建文件...")
    dirs_to_remove = ["build", "dist", "*.egg-info"]
    for pattern in dirs_to_remove:
        for path in Path(".").glob(pattern):
            if path.is_dir():
                shutil.rmtree(path)
                print(f"已删除目录: {path}")
            elif path.is_file():
                path.unlink()
                print(f"已删除文件: {path}")

def build_wheel():
    """构建wheel文件"""
    print("开始构建wheel文件...")
    try:
        # 使用python -m build构建wheel
        result = subprocess.run(
            [sys.executable, "-m", "build", "--wheel"],
            check=True,
            capture_output=True,
            text=True
        )
        print("✓ wheel构建成功")
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print("✗ wheel构建失败")
        print(e.stdout)
        print(e.stderr)
        return False

def list_generated_wheels():
    """列出生成的wheel文件"""
    dist_dir = Path("dist")
    if dist_dir.exists():
        wheels = list(dist_dir.glob("*.whl"))
        if wheels:
            print("\n生成的wheel文件:")
            for wheel in wheels:
                print(f"  - {wheel}")
            return wheels
        else:
            print("未找到生成的wheel文件")
            return []
    else:
        print("未找到dist目录")
        return []

def main():
    """主函数"""
    print("Python示例应用程序 - Wheel打包工具")
    print("=" * 40)
    
    # 检查依赖
    check_prerequisites()
    
    # 清理之前的构建
    clean_previous_builds()
    
    # 构建wheel
    if build_wheel():
        # 列出生成的wheel文件
        wheels = list_generated_wheels()
        if wheels:
            print(f"\n✓ 打包完成! 共生成 {len(wheels)} 个wheel文件")
            return True
        else:
            print("\n⚠ 虽然构建成功，但未找到生成的wheel文件")
            return False
    else:
        print("\n✗ 打包失败!")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)